package com.scfire.weixin
import com.scfire.security.Member
import grails.converters.XML
import grails.plugin.springsecurity.SpringSecurityUtils

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpSession

import net.sf.json.JSONObject

import org.dom4j.Document
import org.dom4j.DocumentHelper;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken
import org.springframework.security.core.Authentication
import org.springframework.security.core.context.SecurityContext
import org.springframework.security.core.context.SecurityContextHolder
import org.springframework.security.core.userdetails.UserDetails

class WeixinController {
	
	def weiXinService
	def springSecurityService
	def userDetailsService
	def deviceInfoService
	/**
	 * 服务器配置
	 * 用户消息和开发者需要的事件推送，回调地址
	 * @return
	 */
	def config() {

		def method = request.getMethod()
		def signature = params.signature
		def timestamp = params.timestamp
		def nonce = params.nonce
		def echostr = params.echostr
		if(method == "GET"){
			if(weiXinService.checkSignature(signature, timestamp, nonce)){
				render echostr
				return
			}
			render ""
			return
		}else if(method == "POST"){
			Map<String, String> map = weiXinService.parseXML(request.getInputStream())
			String msg = weiXinService.event(map, map.get("MsgType") , map.get("Event") , map.get("FromUserName") , map.get("Content") , map.get("CreateTime") , map.get("EventKey"))
			if(msg == ""){
				render ""
				return
			}else{
				response.setContentType("text/xml;charset=UTF-8")
				byte [] data = msg.getBytes("UTF-8")
				OutputStream out = response.getOutputStream()
				out.write(data)
				out.flush()
				out.close()
				return
			}
			
		}
		
	}
	
	/**
	 * 判断登陆类型
	 * @return
	 */
	def login_type_check(){
		def userAgent = request.getHeader("User-Agent")
		
		String ua = ((HttpServletRequest) request).getHeader("user-agent")
		.toLowerCase();
		if (ua.indexOf("micromessenger") > 0) {// 是微信浏览器
			println "微信true"
		  }
		if (ua.indexOf("alipay") > 0) {// 是支付宝浏览器
			println "支付宝true"
		  }
		if (ua.indexOf("weibo") > 0) {// 是支付宝浏览器
			println "新浪true"
		  }
		
		def type = deviceInfoService.getDeviceInfo(userAgent)
		println request.getParameter("aaa")
		if(type.equals("mobile")){
			String oauthCallBack = WeiXinConstants.oauth_url+"?appid="+WeiXinConstants.appid+"&redirect_uri="+URLEncoder.encode(WeiXinConstants.login_url+"?type=微信mobile端")+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"
			redirect(url:oauthCallBack)
			return
		}
		String oauthCallBack = WeiXinConstants.oauth_pc_url+"?appid="+WeiXinConstants.appid_pc+"&redirect_uri="+URLEncoder.encode(WeiXinConstants.login_url+"?type=微信PC端")+"&response_type=code&scope=snsapi_login&state=STATE&#wechat_redirect"
		println oauthCallBack
		redirect(url : oauthCallBack)
		//redirect(url:"/index/toMobile")
		return
		
	}
	
	//login
	def login(){
		def code = params.code
		def type = params.type
		
		JSONObject user
		if(type == "微信mobile端" || type == "微信PC端"){
			if(type == "微信mobile端"){
				user = weiXinService.getUserInfo(code)
			}
			if(type == "微信PC端"){
				render "火堆pc模块待开发！"
				return
//				user = weiXinService.get_pc_userinfo(code)
			}
			println user
			if(user?.errcode){
				String oauthCallBack = WeiXinConstants.oauth_url+"?appid="+WeiXinConstants.appid+"&redirect_uri="+URLEncoder.encode(WeiXinConstants.login_url+"?type=微信mobile端")+"&response_type=code&scope=snsapi_userinfo&state=STATE&connect_redirect=1#wechat_redirect"
				redirect(url:oauthCallBack)
				return
			}else{
			def otherUnionId = session.getAttribute("otherUnionId")
			
			Member member = weiXinService.saveMember(user , type,otherUnionId)
			UserDetails userDetails = userDetailsService.loadUserByUsername(member?.username)
			Authentication authentication = new UsernamePasswordAuthenticationToken(userDetails, userDetails.getPassword(),userDetails.getAuthorities())
			SecurityContext securityContext = SecurityContextHolder.getContext()
			securityContext.setAuthentication(authentication)
			HttpSession session = request.getSession(true)
			session.setAttribute("SPRING_SECURITY_CONTEXT", securityContext)
			}
			
			def url = session.getAttribute("LOGIN_REDIRECT_URL")
			if(url){
				redirect(url: url)
				return
			}
		}
		redirect(uri: "/")
		return
	}
	/**
	 * 创建菜单
	 * @return
	 */
	def createMenu(){
		render weiXinService.createMenu()
	}
}
